package servlet;

import entity.Animal;
import entity.AnimalCategory;
import entity.User;
import service.AnimalCategoryService;
import service.AnimalService;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static UserService userService = new UserService();
    private static AnimalService animalService = new AnimalService();

    private static AnimalCategoryService animalCategoryService = new AnimalCategoryService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userType = request.getParameter("userType");


        User user = userService.login(username, password, Integer.valueOf(userType));
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            //查询所有动物详情
            List<Animal> animals = animalService.getAllAnimals();
            request.setAttribute("animals", animals);

            // 查询所有动物分类
            List<AnimalCategory> categories = animalCategoryService.getAllAnimalCategories();
            request.setAttribute("categories", categories);
            request.getRequestDispatcher("adminIndex.jsp").forward(request, response);
        } else {
            request.setAttribute("errorMessage", "用户名或密码错误");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}
